// pages/parent/supervision/supervision.js
const api = require('../../../utils/api')
const parentApi = require('../../../api/parent')
const auth = require('../../../utils/auth')

Page({
  data: {
    // 孩子列表
    children: [],
    
    // 当前选中的孩子
    selectedChild: null,
    
    // 学习时长统计
    duration: { today: 0, week: 0, month: 0 },
    chartPeriod: 'day',
    chartData: { labels: [], values: [] },
    ec: { lazyLoad: true },
    chart: null,
    
    // 学习进度
    studyProgress: [],
    
    // 课程安排
    courseSchedule: [],
    
    // 作业完成情况
    homeworkStatus: [],
    
    // 学习报告
    studyReports: [],
    
    // 教师评价
    teacherComments: [],
    
    // 加载状态
    loading: false,
    refreshing: false
  },

  onLoad() {
    console.log('学习监督页面加载')
    this.initPage()
  },

  onShow() {
    this.loadData()
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setSelected(2)
    }
  },

  onPullDownRefresh() {
    this.loadData(true).finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 初始化页面
  initPage() {
    this.checkUserRole()
    this.loadChildren()
  },

  // 检查用户角色
  checkUserRole() {
    const app = getApp()
    if (app.globalData.userRole !== 'parent') {
      wx.showModal({
        title: '权限不足',
        content: '您没有权限访问此页面',
        showCancel: false,
        success: () => {
          wx.switchTab({
            url: '/pages/index/index'
          })
        }
      })
    }
  },

  // 加载孩子列表
  async loadChildren() {
    try {
      // 模拟数据，实际应从API获取
      const children = [
        {
          id: 1,
          name: '小明',
          grade: '高一',
          avatar: '/images/default_avatar.png',
          school: '实验中学'
        },
        {
          id: 2,
          name: '小红',
          grade: '初三',
          avatar: '/images/default_avatar.png',
          school: '育才中学'
        }
      ]
      
      this.setData({ 
        children: children,
        selectedChild: children[0] || null
      })
      
      if (children.length > 0) {
        this.loadData()
      }
    } catch (error) {
      console.error('加载孩子列表失败:', error)
    }
  },

  // 加载数据
  async loadData(refresh = false) {
    if (!this.data.selectedChild) return
    
    if (refresh) {
      this.setData({ refreshing: true })
    } else {
      this.setData({ loading: true })
    }

    try {
      await Promise.all([
        this.loadLearningOverview(),
        this.loadStudyProgress(),
        this.loadCourseSchedule(),
        this.loadHomeworkStatus(),
        this.loadStudyReports(),
        this.loadTeacherComments()
      ])
    } catch (error) {
      console.error('加载数据失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ 
        loading: false,
        refreshing: false
      })
    }
  },

  // 切换孩子
  onChildChange(e) {
    const index = e.detail.value
    const selectedChild = this.data.children[index]
    this.setData({ selectedChild })
    this.loadData()
  },

  // 加载学习概况
  async loadLearningOverview() {
    try {
      const storageUser = wx.getStorageSync('user_info') || wx.getStorageSync('userInfo') || {}
      const phone = storageUser.phone || storageUser?.parent_info?.phone || storageUser?.student_info?.phone || storageUser?.teacher_info?.phone
      const res = await parentApi.getStudyStats(this.data.chartPeriod ? { period: this.data.chartPeriod, ...(phone?{ phone }: {}) } : (phone?{ phone }: {}))
      if (res && res.success) {
        const d = res.data || {}
        const duration = d.duration || { today: 0, week: 0, month: 0 }
        const chart = d.chart || { labels: [], values: [] }
        this.setData({ duration, chartData: { labels: chart.labels || [], values: chart.values || [] } }, ()=> this.renderChart())
      }
    } catch (error) { console.error('加载学习概况失败:', error) }
  },

  // 切换图表周期
  switchPeriod(e){
    const key = e.currentTarget.dataset.key
    this.setData({ chartPeriod: key }, ()=> this.loadLearningOverview())
  },

  // 渲染折线图（wx-echarts）
  renderChart(){
    try{
      if (!this.selectComponent) return
      const ecComp = this.selectComponent('#studyChart')
      if (!ecComp) return
      const { labels, values } = this.data.chartData
      const option = {
        grid: { left: 30, right: 20, top: 20, bottom: 30 },
        xAxis: { type: 'category', data: labels, boundaryGap: false, axisLine:{lineStyle:{color:'#ddd'}}, axisLabel:{color:'#666'} },
        yAxis: { type: 'value', axisLine:{show:false}, splitLine:{lineStyle:{color:'#f0f0f0'}}, axisLabel:{color:'#888'} },
        series: [{ type: 'line', smooth: true, data: values, areaStyle:{color:'rgba(76,175,80,0.15)'}, lineStyle:{color:'#4CAF50'}, itemStyle:{color:'#4CAF50'} }]
      }
      if (this.data.chart) {
        this.data.chart.setOption(option, true)
        return
      }
      ecComp.init((canvas, width, height, dpr)=>{
        const echarts = require('../../../../ec-canvas/echarts')
        const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr })
        chart.setOption(option)
        this.setData({ chart })
        return chart
      })
    }catch(e){ console.error('渲染图表失败', e) }
  },

  // 加载学习进度
  async loadStudyProgress() {
    try {
      // 模拟数据
      const progress = [
        {
          subject: '数学',
          progress: 75,
          nextLesson: '函数与方程',
          teacher: '张老师'
        },
        {
          subject: '英语',
          progress: 60,
          nextLesson: '阅读理解',
          teacher: '李老师'
        },
        {
          subject: '物理',
          progress: 80,
          nextLesson: '电磁感应',
          teacher: '王老师'
        }
      ]
      
      this.setData({ studyProgress: progress })
    } catch (error) {
      console.error('加载学习进度失败:', error)
    }
  },

  // 加载课程安排
  async loadCourseSchedule() {
    try {
      // 模拟数据
      const schedule = [
        {
          id: 1,
          date: '今天',
          time: '14:00-15:00',
          subject: '数学',
          teacher: '张老师',
          type: '一对一',
          status: 'upcoming'
        },
        {
          id: 2,
          date: '明天',
          time: '16:00-17:00',
          subject: '英语',
          teacher: '李老师',
          type: '小班课',
          status: 'scheduled'
        }
      ]
      
      this.setData({ courseSchedule: schedule })
    } catch (error) {
      console.error('加载课程安排失败:', error)
    }
  },

  // 加载作业状态
  async loadHomeworkStatus() {
    try {
      // 模拟数据
      const homework = [
        {
          id: 1,
          subject: '数学',
          title: '二次函数练习',
          deadline: '今天 18:00',
          status: 'pending',
          score: null
        },
        {
          id: 2,
          subject: '英语',
          title: '阅读理解A篇',
          deadline: '昨天 20:00',
          status: 'completed',
          score: 92
        }
      ]
      
      this.setData({ homeworkStatus: homework })
    } catch (error) {
      console.error('加载作业状态失败:', error)
    }
  },

  // 加载学习报告
  async loadStudyReports() {
    try {
      // 模拟数据
      const reports = [
        {
          id: 1,
          title: '本周学习报告',
          date: '2024-01-15',
          type: 'weekly',
          summary: '本周学习状态良好，数学和英语进步明显'
        },
        {
          id: 2,
          title: '月度学习分析',
          date: '2024-01-01',
          type: 'monthly',
          summary: '整体表现优秀，建议加强物理学习'
        }
      ]
      
      this.setData({ studyReports: reports })
    } catch (error) {
      console.error('加载学习报告失败:', error)
    }
  },

  // 加载教师评价
  async loadTeacherComments() {
    try {
      // 模拟数据
      const comments = [
        {
          id: 1,
          teacher: '张老师',
          subject: '数学',
          date: '2024-01-20',
          comment: '小明在数学方面表现出色，逻辑思维能力强，建议继续保持。',
          rating: 5
        },
        {
          id: 2,
          teacher: '李老师',
          subject: '英语',
          date: '2024-01-19',
          comment: '英语口语有所提高，建议多进行听力练习。',
          rating: 4
        }
      ]
      
      this.setData({ teacherComments: comments })
    } catch (error) {
      console.error('加载教师评价失败:', error)
    }
  },

  // 查看详细报告
  viewReport(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/parent/study-report/study-report?id=${id}`
    })
  },

  // 查看课程详情
  viewCourse(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/courses/detail?id=${id}`
    })
  },

  // 联系教师
  contactTeacher(e) {
    const teacher = e.currentTarget.dataset.teacher
    wx.showModal({
      title: '联系教师',
      content: `确定要联系${teacher}吗？`,
      success: (res) => {
        if (res.confirm) {
          // 跳转到聊天页面或拨打电话
          wx.showToast({
            title: '功能开发中',
            icon: 'none'
          })
        }
      }
    })
  },

  // 设置学习提醒
  setReminder() {
    wx.navigateTo({
      url: '/pages/parent/reminder/reminder'
    })
  },

  // 页面分享
  onShareAppMessage() {
    return {
      title: '学习监督',
      path: '/pages/parent/supervision/supervision'
    }
  }
})